package com.example.parsexml;
import android.util.Log;
import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;

import java.util.ArrayList;
import java.util.List;
/**
 * project:
 * author: wzq
 * date: 2014/7/31
 * description: SaxHandler 与数据模型密切关联
 */
public class SaxHandler extends DefaultHandler {
    private List<ModelStu> stuList; // 最终返回的结果 应该与xml对应

    private ModelStu tmpStu;
    private boolean inName;
    private boolean inAge;
    private boolean inSex;

    public List<ModelStu> getData() {
        return stuList;
    }

    @Override
    public void startDocument() throws SAXException {
        stuList = new ArrayList<ModelStu>();
    }

    @Override
    public void endDocument() throws SAXException {
    }

    // 使用localName, 关于这点，请看笔记
    @Override
    public void startElement(String namespaceURI, String localName, String qName, Attributes atts) throws SAXException {
        Log.i("saxHandler", "local=" + localName + ",qName=" + qName);
        // stu_sax 节点开始
        if("stu".equals(localName)) {
            tmpStu = new ModelStu();
            String id = atts.getValue("id");//TODO 获取 id 属性值
            tmpStu.setId(id);
        }
        //
        else if("name".equals(localName)) {
            inName = true;
        }
        //
        else if("age".equals(localName)) {
            inAge = true;
        }
        //
        else if("sex".equals(localName)) {
            inSex = true;
        }

    }

    @Override
    public void endElement(String namespaceURI, String localName, String qName) throws SAXException {
        // stu_sax 节点结束
        if("stu".equals(localName)) {
            if(tmpStu != null) {
                stuList.add(tmpStu);
                tmpStu = null;
            }
        } else if("name".equals(localName)) {
            inName = false;
        } else if("age".equals(localName)) {
            inAge = false;
        } else if("sex".equals(localName)) {
            inSex = false;
        }
    }

    @Override
    public void characters(char ch[], int start, int length) {
        String chars = new String(ch, start, length);
        chars = chars.trim();

        if(inName && tmpStu != null) {
            tmpStu.setName(chars);
        } else if(inAge && tmpStu != null) {
            int age = Integer.parseInt(chars);
            tmpStu.setAge(age);
        } else if(inSex && tmpStu != null) {
            tmpStu.setSex(chars);
        }
    }
}